import OSS from 'ali-oss'
import { parseTime, random_string } from '@utils/index'

// 上传文件或base64图片到阿里云OSS
export const uploadFileToOSS = async ({ file }) => {
    // 根据类型选择存储信息
    const client = new OSS({
        region: 'oss-cn-heyuan',
        accessKeyId: 'LTAI5t9cTADXLaX7BGJD33EE',
        accessKeySecret: 'LSt9jmp1zkq6gyktwdVWFYJ1kscYnc',
        bucket: 'verify-merchant'
    })

    // 处理file参数，将base64转换为Blob
    let uploadFile = file
    let extension = 'png'  // 默认扩展名

    if (typeof file === 'string') {
        const byteString = atob(file.split(',')[1])
        const mimeString = file.split(',')[0].split(':')[1].split(';')[0]
        const ab = new ArrayBuffer(byteString.length)
        const ia = new Uint8Array(ab)
        for (let i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i)
        }
        uploadFile = new Blob([ab], { type: mimeString })
        // 从MIME类型获取扩展名
        extension = mimeString.split('/')[1]
    } else {
        // 如果是文件类型，从文件名获取扩展名
        extension = file.name.split('.').pop()
    }

    const fileName = `${parseTime(new Date(), '{y}{m}{d}')}_${random_string()}.${extension}`
    console.log(uploadFile instanceof Blob, uploadFile,  extension, fileName)
    return new Promise((resolve, reject) => {
        client
            .multipartUpload(fileName, uploadFile)
            .then((result) => {
                resolve(result)
            })
            .catch((err) => {
                reject(err)
            })
    })
}
